<template>

</template>
<script lang="ts">
import { token, user } from '@/util/storage';
import Vue from 'vue'
export default Vue.extend({
  data() {
    return {
      redirect: ""
    };
  },
  onLoad(option) {
    console.log("option", option)
    if (option) {
      if (option.redirect) {
        this.redirect = option.redirect;
      }
      if (option.state) {
        this.redirect = option.state;
      }
      if (option.code) {
        this.sendWechatCodeToBackend(option.code);
      } else {
        this.wechatAuth();
      }
    }
  },
  mounted() {
  },
  methods: {
    wechatAuth() {
      location.href = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + this.$config.WEIXIN_APP_ID + "&redirect_uri=http%3A%2F%2Fh5.yangpihu.net%2F&response_type=code&scope=snsapi_userinfo&state=" + this.redirect + "#wechat_redirect";
    },
    getSelfInfo(data: any) {
      user.set(data);
      this.toIndexPage();
    },
    sendWechatCodeToBackend(code: string) {
      uni.showLoading({
        title: "微信登录中",
      });
      this.$mainApi.apiWxCodeLogin(code).then((res) => {
        uni.hideLoading();
        uni.showToast({
          title: "微信登录成功" + JSON.stringify(res.data),
        });
        if (!res.data.mobileNumber) {
          this.toBindPage(res.data.wxInfoId);
        } else {
          token.set(res.data.token);
          this.getSelfInfo(res.data);
        }
      });
    },
    toIndexPage() {
      let url = "/pages/items/index";
      if (this.redirect) {
        url = decodeURI(this.redirect);
      }
      location.href = "/#" + url;
    },
    toBindPage(wxInfoId: string) {
      location.href = "/#/pages/login/bind?wxinfoid=" +
        wxInfoId +
        "&redirect=" +
        this.redirect;
    },
    toPasswordPage() {
      location.href = "/#/pages/login/password?redirect=" + this.redirect;
    }
  }
})
</script>
<style lang="scss" scoped>

</style>
